package com.atguigu.gmall.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.product.client.model.enums.ProcessStatus;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

//减库存

@Component
public class DecrStockConsumer {
    @Autowired
    private OrderInfoService orderInfoService;

    //减库存之后  更新订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void decrStockAndUpdateOrderStatus(String jsonMap, Message message, Channel channel){

        try {
            Map map = JSONObject.parseObject(jsonMap,Map.class);  //将string类型 转换为map类型
            if ("DEDUCTED".equals(map.get("status"))){
                //减库存成功
                //更新订单状态                                       先把object转为string类型 然后在转为long类型
                orderInfoService.updateOrderStatus(Long.parseLong(String.valueOf(map.get("orderId"))),
                        ProcessStatus.WAITING_DELEVER);
            }else{
                //减库存异常
                orderInfoService.updateOrderStatus(Long.parseLong(String.valueOf(map.get("orderId"))),
                        ProcessStatus.STOCK_EXCEPTION);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
